package com.app.admin.service;

import com.app.admin.repository.SystemSettingRepository;
import com.app.common.entity.SystemSetting;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class SystemSettingService {
    private final SystemSettingRepository settingRepository;


    // 获取所有配置，转换为 Map<String, String>
    public Map<String, String> getAllSettings() {
        List<Map<String, Object>> listOfMaps = settingRepository.findAllAsListOfMaps();
        Map<String, String> resultMap = new HashMap<>();

        // 遍历列表，将每条记录的 key 和 value 放入结果 Map
        for (Map<String, Object> map : listOfMaps) {
            String key = (String) map.get("key"); // 对应查询中的 s.configKey as key
            String value = (String) map.get("value"); // 对应查询中的 s.configValue as value
            resultMap.put(key, value);
        }
        return resultMap;
    }

    // 更新配置（如果不存在则新增）
    @Transactional
    public void updateSetting(String configKey, String configValue) {
        SystemSetting setting = settingRepository.findByConfigKey(configKey)
                .orElse(new SystemSetting()); // 不存在则创建新对象
        setting.setConfigKey(configKey);
        setting.setConfigValue(configValue);
        settingRepository.save(setting);
    }

    // 批量更新配置
    @Transactional
    public void batchUpdateSettings(Map<String, String> settings) {
        settings.forEach(this::updateSetting);
    }
}
